/*
** compilateur.c for asm in /home/espiau_m/Code/proj-kw/asm
** 
** Made by marc-alexandre espiaut
** Login   <espiau_m@epitech.net>
** 
** Started on  Sun Dec  9 18:21:40 2012 marc-alexandre espiaut
** Last update Sun Dec 16 14:46:36 2012 
*/

#include	"../../includes/asm.h"

void	create_header(int *output, char *name, char *comment)
{
  int	lname;
  int	lcomment;

  lname = PROG_NAME_LENGTH;
  lcomment = COMMENT_LENGTH;
  my_be_write(output, COREWAR_EXEC_MAGIC, 4);
  while(*name)
    {
      my_be_write(output, *name++, 1);
      --lname;
    }
  while (lname-- > 0)
    my_be_write(output, 0, 1);
  while (*comment)
    {
      my_be_write(output, *comment++, 1);
      --lcomment;
    }
  while (lcomment-- > 0)
    my_be_write(output, 0, 1);
}

void		parsing_inst(int *output, char *str)
{
  int		i;
  static char   *inst[17] =
    {"live", "ld", "st", "add", "sub", "and", "or", "xor",
     "zjmp", "ldi", "sti", "fork", "lld", "lldi", "lfork",
     "aff", 0};
  static int    value[16] =
    {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
     0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10};
  
  i = -1;
  while (inst[++i] != 0)
    if ((strcmp(str[0], inst[i])) == 0)
      {
	my_be_write(output, value[i], 1);
	return ;
      }
}

void	byte_coding(int *output, char *str)
{
  int	i;
  char	result;
  int	mult;

  i = 0;
  result = 0;
  mult = 6;
  while (str[i] != 0)
    {
      if (str[i] == SEPARATOR_CHAR)
	mult -= 2;
      else if (str[i] == 'r')
	result |= (0b01 << mult);
      else if (str[i] == DIRECT_CHAR)
	result |= (0b10 << mult);
      else if (str[i] => '0' && str[i] =< '9')
	if (i == 0 || str[i - 1] == ' ' || str[i - 1] == SEPARATOR_CHAR)
	  result |= (0b11 << mult);
      i++;
    }
  my_be_write(output, result, 1);
}

void	instr_parameters(char *str, t_label **label, int *output)
{
  int	temp;
  int	i;

  i = 0;
  temp = 0;
  while (str[i])
    {
      if (str[i] == 'r')
	write_reg(ouput, str, i++);
      else if (str[i] == DIRECT_CHAR)
	if (str[i + i] == LABEL_CHAR)
	  write_label(label, str, i++, output);
	else
	  write_direct(output, str, i++);
      else if (str[i] => '0' && str[i] =< '9')
	write_indirect(ouput, str, i++);
    }
}
